<?php

class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract
{

    protected $_name = 'users';
    public function getUser($id) {
        $id = (int) $id;
        $row = $this->fetchRow('id = ' . $id);
        if (!$row) {
            throw new Exception("Could not find row $id");
        }
        return $row->toArray();
    }

    public function addUser($username, $email, $password, $role="administrator") {
        // gera um id único para a senha
        $salt = 'ce8d96d579d389e783f95b3772785783ea1a9854';
        // cria um hash de senha para gravar no banco
        //$hashed_pwd = strtolower(sha1($password . $salt));
        $hashed_pwd = sha1($password.$salt);

        $data = array(
            'username' => $username,
            'email' => $email,
            'password' => $hashed_pwd,
            'salt' => $salt,
            'role' => $role,
            'date_created' => date('Y-m-d H:i:s')
        );

        $this->insert($data);
    }

    public function updateUser($id, $username, $email, $password=null, $role="administrator") {
        $where = array('id = ?' => (int) $id);
        $salt = 'ce8d96d579d389e783f95b3772785783ea1a9854';
        $data = array('username' => $username, 'email' => $email, 'role' => $role);
        if ($password !== null) {
            $hashed_pwd = sha1($password . $salt);
            $data['salt'] = $salt;
            $data['password'] = $hashed_pwd;
        }
        $this->update($data, $where);
    }

    public function deleteUser($id) {
        $this->delete('id =' . (int) $id);
    }

}

